/**
* This file is part of tictionary.
*
* tictionary is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* You should have received a copy of the GNU General Public License
* along with dev.clipall.  If not, see <http://www.gnu.org/licenses/>.
*
* http://code.google.com/p/tictionary/
*/

package tictionary;

/**
 *
 * @author Erol Hira
 */
public class StringUtils {
        
    //-------------------------------------------------------------------
    // Begin : String Utils    
    //-------------------------------------------------------------------

    public static int countOfCharInString(String str, char ch){ 

        int cnt = 0;
        for(int i = 0; i < str.length(); i++){
            if(str.charAt(i) == ch){
                cnt ++;
            }
        }

        return cnt;
    }

    /*
    *   tokenIndex starts from 1 
    **/
    public static String getToken(String str, char delimiter, int tokenIndex){

        int tokenCnt = getTokenCount(str, delimiter);

        if(tokenIndex > tokenCnt || tokenIndex == 0){

            return null;

        } else {

            return str.substring(
                    getTokenStartIndex(str, delimiter, tokenIndex),
                    getTokenFinishIndex(str, delimiter, tokenIndex)
                    );
        }
    }

    /**
     * tokenIndex starts from 1
     * start index of a token.
     */    
    public static int getTokenStartIndex(String str, char ch, int tokenIndex){        

        if(tokenIndex == 1){

            return 0;
            
        } else {

            return nthIndexOf(str, ch, tokenIndex - 1) + 1;
        }
    }

    /**
     * returns exclusive last index
     *
     */
    public static int getTokenFinishIndex(String str, char ch, int tokenIndex){

        if(getTokenCount(str, ch) == tokenIndex){

            return str.length();

        } else {

            return nthIndexOf(str, ch, tokenIndex);

        }
    }

    public static int getTokenCount(String str, char ch){
        return countOfCharInString(str, ch) + 1;
    }

    public static int nthIndexOf(String str, char ch, int n){

        int cnt = 0;
        
        for(int i = 0; i < str.length(); i++){

            if(str.charAt(i) == ch){

                cnt ++;

                if(cnt == n){
                    return i;                    
                }
            }
        }

        return -1;
    }

    //-------------------------------------------------------------------
    // End : String Utils    
    //-------------------------------------------------------------------
}
